package com.example.everying.controller.user;/*
 * 项目名称: everything
 * 文件名: UserController
 * 作者: 张泽阳
 * 日期: 2025/5/20
 * 描述:
 */

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.everying.annotation.WebLog;
import com.example.everying.constant.CacheConstants;
import com.example.everying.context.UserContext;
import com.example.everying.model.dto.user.*;
import com.example.everying.model.entity.user.PointsAccount;
import com.example.everying.model.entity.user.UserBalanceEntity;
import com.example.everying.model.entity.user.UserEntity;
import com.example.everying.model.vo.user.UserInfoVo;
import com.example.everying.model.vo.user.UserPageWithBalance;
import com.example.everying.service.user.PointsAccountService;
import com.example.everying.service.user.UserBalanceService;
import com.example.everying.service.user.UserService;
import com.example.everying.utils.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.implementation.bind.annotation.Default;
import org.apache.catalina.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private UserBalanceService userBalanceService;
    @Autowired
    private RedisUtils redisCache;

    @Autowired
    private ImageUpload imageUpload;

    @Autowired
    private PointsAccountService pointsAccountService;

    @WebLog(description = "用户分页")
    @PostMapping("/page")
    public Result list(@RequestBody UserPageDto userPageDto) {
        return userService.list(userPageDto);
    }

    @WebLog(description = "验证用户认证状态")
    @PostMapping("/checkUserAuth")
    public Result<?> checkUserAuth() {
        UserInfoVo userInfoVo = UserContext.getUser();
        if (userInfoVo == null) { 
            return Result.fail("请先登录");
        }
        
        // 获取用户完整信息
        UserEntity userEntity = userService.getById(userInfoVo.getId());
        if (userEntity == null) {
            return Result.fail("用户不存在");
        }
        
        // 返回认证状态
        Map<String, Object> response = new HashMap<>();
        response.put("isUserAuth", userEntity.isUserAuth());
        response.put("userId", userEntity.getId());
        
        return Result.ok(response);
    }

    @WebLog(description = "关联余额分类")
    @PostMapping("/list")
    public Result<?> listWithBalance(@RequestBody UserPageDto userPageDto) {
        Page<UserInfoVo> pageParam = new Page<>(userPageDto.getPage(), userPageDto.getLimit());
        return userService.selectPageWithBalance(pageParam, userPageDto);
    }

    @WebLog(description = "编辑用户信息")
    @PostMapping("/userEdit")
    public Result UserEdit(@RequestBody @Validated UserEditDto userEditDto) {
        UserInfoVo userInfoVo = userService.userEdit(userEditDto);
        return Result.ok(userInfoVo);
    }

    @WebLog(description = "查询用户信息")
    @PostMapping("/getUserById")
    public Result getUserById(@RequestBody(required = false) GetUserByIdDto getUserByIdDto) {
        log.info("获取用户信息/user/getUserById======");
        String userId = null;
        if (getUserByIdDto == null || getUserByIdDto.getId() == null) {
             log.info("获取用户信息/user/getUserById返回信息====== {}", UserContext.getUser().toString());
            UserInfoVo userInfoVo = UserContext.getUser();
            // UserInfoVo userInfoVo = userService.getUserById(getUserByIdDto.getId());

            userId = userInfoVo.getId();
            // 获取余额
            UserBalanceEntity userBalanceEntity = userBalanceService.getBalanceByUserId(userId);
            userInfoVo.setBalance(userBalanceEntity.getAvailableAmount());
            // todo 默认中关村
            userInfoVo.setSchoolName("中关村科技园");
            if (userInfoVo.getPayPassword() == null) {
                userInfoVo.setPayPassword("");
            }
            return Result.ok(userInfoVo);
        }
        UserInfoVo userInfoVo = userService.getUserById(getUserByIdDto.getId());
        // todo 默认中关村
        userInfoVo.setSchoolName("中关村科技园");
        userId = userInfoVo.getId();
        //log.info("获取用户信息/user/getUserById返回信息======{}",  userInfoVo.toString());
        // 获取余额
        UserBalanceEntity userBalanceEntity = userBalanceService.getBalanceByUserId(userId);
        userInfoVo.setBalance(userBalanceEntity.getAvailableAmount());
        if (userInfoVo.getPayPassword() == null) {
            userInfoVo.setPayPassword("");
        }
        return Result.ok(userInfoVo);
    }

    @WebLog(description = "学生认证")
    @PostMapping("/updateInformation")
    public Result updateInformation(@RequestBody @Validated UpdateInformationDto updateInformationDto) {
        // UserInfoVo userInfoVo = userService.updateInformation(updateInformationDto);
        return userService.updateInformation(updateInformationDto);
    }
    @WebLog(description = "实名认证")
    @PostMapping("/auth")
    public Result<?> auth(@RequestBody @Validated AuthDto authDto) {
        return userService.auth(authDto);
    }

    @WebLog(description = "上传图片")
    @PostMapping("/upload")
    public Result<?> uploadImages(@RequestParam("files") MultipartFile[] files) throws IOException {
        List<String> list = imageUpload.uploadImages(files);
        if (list.isEmpty()) {
            return Result.fail("上传失败");
        }
        return Result.ok(list);
    }

    @WebLog(description = "修改头像")
    @PostMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam("files") MultipartFile[] files) throws IOException {
        List<String> list = imageUpload.uploadImages(files);
        UserEditDto userEditDto = new UserEditDto();
        userEditDto.setAvatarUrl(list.get(0));
        userEditDto.setId(UserContext.getUser().getId());
        UserInfoVo userInfoVo = userService.userEdit(userEditDto);
        return Result.ok(userInfoVo);
    }


    @WebLog(description = "删除用户")
    @PostMapping("/deleteUser")
    public Result deleteUser(@RequestBody DeleteUserDto ids) {
        boolean flag = userService.deleteUser(ids);
        return Result.ok(flag);
    }

    @WebLog(description = "上传位置")
    @PostMapping("/uploadLoaction")
    public Result uploadLoaction(@RequestBody UploadLocationDto location) {
        boolean flag = userService.uploadLocation(location);
        return Result.ok(flag);
    }

    @WebLog(description = "新增用户")
    @PostMapping("/addUser")
    public Result<?> addUser(@RequestBody UserEntity user) {
        if (UserContext.getUser().getIsAdministrator() != 1) {
            return Result.fail("权限不足");
        }
        return userService.addUser(user);
    }

    /**
     * 发送短信验证码
     *
     * @return AjaxResult
     */
    @PostMapping("/sms/send")
    @WebLog(description = "发送短信验证码")
    public Result<?> sendSms() {
        UserInfoVo userInfoVo = UserContext.getUser();
        // 生成6位随机验证码
        String code = String.valueOf(new Random().nextInt(899999) + 100000);

        String key = CacheConstants.SMS_CODE + userInfoVo.getId() + ":" + code;
        // 将验证码存入 Redis，有效期5分钟
        log.info("redid key：{}", key);
        redisCache.setCacheObject(key, code, 5, TimeUnit.MINUTES);
        SmsUtil.sendMsg(userInfoVo.getPhone(), code);

        return Result.ok("验证码发送成功");
    }

    @PostMapping("/password/pay/verify")
    @WebLog(description = "校验支付密码")
    public Result<?> verify(@RequestBody UserEntity user) {
        UserInfoVo userInfoVo = UserContext.getUser();
        if (userInfoVo.getPayPassword().isEmpty()) {
            throw new CampusException("请先设置支付密码", 201);
        }
        if (user.getPayPassword().isEmpty()) {
            throw new CampusException("请输入支付密码", 201);
        }
        return userService.verifyPassword(userInfoVo.getId(), user.getPayPassword()) ? Result.ok("验证成功") : Result.fail("验证失败");
    }
    @PostMapping("/password/pay/update")
    @WebLog(description = "更新支付密码")
    public Result<?> passwordUpdate(@RequestBody PasswordUpdateDto updateDto, HttpServletRequest request) {
        UserInfoVo userInfoVo = UserContext.getUser();
        if (userInfoVo == null) {
            throw new CampusException("请先登录", 201);
        }
        updateDto.setUserId(userInfoVo.getId());
        String token = request.getHeader("Authorization");
        updateDto.setToken(token);
        return userService.passwordUpdate(updateDto) ? Result.ok("修改成功") : Result.fail("修改失败");
    }

    @PostMapping("/verify")
    public ResponseEntity<Map<String, Object>> verifyIdentity(@RequestBody AuthDto authDto) {
        boolean verified = userService.verifyIdentity(authDto.getRealName(), authDto.getIdCard(),authDto.getId());

        Map<String, Object> response = new HashMap<>();
        response.put("success", verified);
        response.put("message", verified ? "验证通过" : "验证失败");

        return ResponseEntity.ok(response);
    }

    @WebLog(description = "绑定微信")
    @PostMapping("/bindeWx")
    public Result<?> bindeWx(@RequestBody @Validated BindWxDto bindWxDto) {
        return userService.bindWx(bindWxDto);
    }

}
